package dexter.net;

import dexter.core.host.HostAddress;
import dexter.net.msg.BusMessage;
import dexter.net.msg.common.BusListener;
import dexter.net.node.AbstractNode;

public class Bus implements BusListener {

	private Consumer consumer;
	private AbstractNode node;
	
	public Bus(AbstractNode node) {		
		this.node = node;
		this.consumer = new Consumer(node.getHostAddress());
		try {
		  consumer.receive(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void send(HostAddress host, BusMessage msg) {
		//System.out.println("Bus send : "+msg);
		
		if (node.getHostAddress().equals(host)) {
			//System.out.println("Reciproc message : "+msg);
			final BusMessage selfMsg = msg;
			new Thread() {
			  public void run() {
				  try {
				    receive(selfMsg);
				  } catch(Exception e) {
					  e.printStackTrace();
				  }
			  }
			}.start();			
		}
	
		else {
		  Producer producer = new Producer(host);
		  producer.send(host, msg);
		}  
	}

	public void receive(BusMessage msg) throws Exception {
		//System.out.println("Bus receive : "+msg);
		node.messageArrive(msg);
		
	}
	
	public void close() {
		consumer.close();
	}

	
}
